//
//  DMBannerManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/7/9.
//

#import "DMBannerManager.h"
#import "../DMBannerScenes.h"
#import <UIKit/UIKit.h>
#import <IronSource/IronSource.h>
#import "IMLogUtils.h"
#import "DMConfigReader.h"
#import "IMAdStrategyManager.h"
#import "DMAdDelegate.h"
#import "DMThinkingManager.h"
#import "DMCommercialManager.h"
#import <AdjustSdk/AdjustSdk.h>


// DMBannerScene 到 IMAdScene 的转换函数
static IMAdScene IMAdSceneFromDMBannerScene(DMBannerScene bannerScene) {
    switch (bannerScene) {
        case DMBannerSceneInit:
            return IMAdSceneBannerInit;
        case DMBannerSceneLevelEnter:
            return IMAdSceneBannerLevelEnter;
        case DMBannerSceneGameStart:
            return IMAdSceneLevelStart;
        case DMBannerSceneLevelComplete:
            return IMAdSceneLevelWin;
        case DMBannerSceneLevelFail:
            return IMAdSceneLevelFail;
        case DMBannerSceneGamePause:
            return IMAdSceneLevelWait;
        case DMBannerSceneMainMenu:
            return IMAdSceneBannerLevelEnter;
        case DMBannerSceneShop:
            return IMAdSceneBannerLevelEnter;
        case DMBannerSceneSettings:
            return IMAdSceneBannerLevelEnter;
        default:
            return IMAdSceneBannerLevelEnter;
    }
}

@interface DMBannerManager()<LPMBannerAdViewDelegate>
@property (nonatomic, assign) BOOL hasShowAd;
@property (nonatomic, assign)BOOL isReloadBanner;
@property (nonatomic, assign)BOOL isTop;//banner是否顶部
@property (nonatomic, assign)BOOL isUserClosed;//用户是否主动关闭了广告
@property (nonatomic, assign)NSTimeInterval showRequestTime;//展示请求时间戳
@property (nonatomic, strong) LPMBannerAdView *lpmBannerAdView;
// 事件打点相关属性
@property (nonatomic, assign) NSTimeInterval loadStartTime; // 加载开始时间
@property (nonatomic, copy) NSString *currentAdUnitId; // 当前广告位ID
@property (nonatomic, copy) NSString *currentAdScene; // 当前广告场景

// 双广告位支持的私有属性
@property (nonatomic, strong) LPMBannerAdView *primaryBannerAdView;
@property (nonatomic, strong) LPMBannerAdView *secondaryBannerAdView;
@property (nonatomic, assign) BOOL isLoadingPrimary;
@property (nonatomic, assign) BOOL isLoadingSecondary;
@property (nonatomic, assign) NSTimeInterval primaryAdLoadTime;
@property (nonatomic, assign) NSTimeInterval secondaryAdLoadTime;
@property (nonatomic, strong) NSString *currentSecondaryAdUnitId;

@end
@implementation DMBannerManager

// 保持对外接口一致性的 getter 方法
- (LPMBannerAdView *)bannerView {
    return self.lpmBannerAdView;
}
static DMBannerManager *_banner = nil;
+ (instancetype)shareBannerManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _banner = [[self alloc] init];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 单例管理器创建成功"];
        
        // 检查是否启用双广告位配置
        _banner.isDualAdEnabled = [DMCommercialManager isDualAdEnabledForAdType:@"banner"];
        
        if (_banner.isDualAdEnabled) {
            // 获取主备广告位ID
            _banner.currentPrimaryAdUnitId = [DMConfigReader primaryBannerAdUnitId];
            _banner.currentSecondaryAdUnitId = [DMConfigReader secondaryBannerAdUnitId];
            
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 双广告位模式启用"];
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 主广告位ID: %@", _banner.currentPrimaryAdUnitId];
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 备用广告位ID: %@", _banner.currentSecondaryAdUnitId];
            
            // 初始化双广告位状态
            _banner.isPrimaryAdLoaded = NO;
            _banner.isSecondaryAdLoaded = NO;
            _banner.isLoadingPrimary = NO;
            _banner.isLoadingSecondary = NO;
            _banner.primaryAdECPM = 0.0;
            _banner.secondaryAdECPM = 0.0;
        } else {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 单广告位模式"];
        }
    });
    return _banner;
}

- (void)preloadBannerOnly {
    // 仅预加载：不受 isUserClosed 限制，不触发展示
    if (self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 预加载模式：双广告位开始预加载"];
        [self loadDualBannerAds];
        return;
    }

    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 预加载模式：单广告位开始预加载"];

    // 记录加载开始时间
    self.loadStartTime = [[NSDate date] timeIntervalSince1970];

    // 从配置获取Banner广告位ID
    DMConfigReader *configReader = [DMConfigReader sharedInstance];
    DMAdUnitConfig *bannerConfig = [configReader adUnitConfigForType:@"Banner" sdkType:@"IS" isLow:NO];
    NSString *adUnitId = [[DMConfigReader sharedInstance]bannerAdConfigs][0].ad_unitID;
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] (预加载) 使用广告位ID: %@", adUnitId];
    self.currentAdUnitId = adUnitId;

    // SDK_ad_fill_request 广告预加载事件打点
    NSDictionary *fillRequestParams = @{
        @"w_ad_type": @"banner",
        @"w_ad_unit_id": adUnitId ?: @"",
        @"w_preload": @1
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] (预加载) 事件打点: SDK_ad_fill_request"];

    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController *rootViewController = [self topViewController];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] (预加载) 获取根控制器: %@", rootViewController];

        // 创建 LPMBannerAdView（带尺寸配置，避免0x0）
        LPMAdSize *adSize = [LPMAdSize bannerSize];
        LPMBannerAdViewConfig *config = [[[[LPMBannerAdViewConfigBuilder alloc] init] setWithAdSize:adSize] build];
        self.lpmBannerAdView = [[LPMBannerAdView alloc] initWithAdUnitId:self.currentAdUnitId config:config];
        self.lpmBannerAdView.frame = CGRectMake(0, 0, adSize.width, adSize.height);
        [self.lpmBannerAdView setDelegate:self];

        // 仅加载，不展示
        [self.lpmBannerAdView loadAdWithViewController:rootViewController];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] (预加载) 已触发 loadAdWithViewController"];
    });
}

- (void)loadBanner
{
    if (self.isUserClosed) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ❌ 用户已主动关闭广告，拒绝加载新广告"];
        return;
    }
    
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ========== 开始加载横幅广告 =========="];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 埋点事件已发送: adLoad"];
    
    // 记录加载开始时间
    self.loadStartTime = [[NSDate date] timeIntervalSince1970];
    
    // 从配置获取Banner广告位ID
    DMConfigReader *configReader = [DMConfigReader sharedInstance];
    DMAdUnitConfig *bannerConfig = [configReader adUnitConfigForType:@"Banner" sdkType:@"IS" isLow:NO];
    NSString *adUnitId = [[DMConfigReader sharedInstance]bannerAdConfigs][0].ad_unitID;
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 使用广告位ID: %@", adUnitId];
    self.currentAdUnitId = adUnitId;
    
    // SDK_ad_fill_request 广告预加载事件打点
    NSDictionary *fillRequestParams = @{
        @"w_ad_type": @"banner",
        @"w_ad_unit_id": adUnitId ?: @""
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_fill_request"];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController *rootViewController = [self topViewController];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 获取根控制器: %@", rootViewController];
        
        // 创建 LPMBannerAdView
        LPMAdSize *adSize = [LPMAdSize bannerSize];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 创建自适应广告尺寸: %@", adSize];
        
        LPMBannerAdViewConfig *config = [[[[LPMBannerAdViewConfigBuilder alloc] init] setWithAdSize:adSize] build];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 创建 Banner 配置完成"];

        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 创建 LPMBannerAdView 实例"];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] AdUnit ID: %@", self.currentAdUnitId];
        
        self.lpmBannerAdView = [[LPMBannerAdView alloc] initWithAdUnitId:self.currentAdUnitId config:config];
        self.lpmBannerAdView.frame = CGRectMake(0, 0, adSize.width, adSize.height);
        [self.lpmBannerAdView setDelegate:self];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 设置代理完成: %@", self];
        
        [self.lpmBannerAdView loadAdWithViewController:rootViewController];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 调用 loadAdWithViewController 开始加载广告"];
    });
}

- (void)reLoad
{
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ⏰ 开始延迟重新加载 (5秒后)"];
    if (self.isUserClosed) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ❌ 用户已主动关闭广告，取消重新加载"];
        return;
    }
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 🔄 5秒延迟结束，开始重新加载横幅广告"];
    // 使用智能重试机制
    if ([self shouldRetry]) {
        [self scheduleRetryWithDelay:[self calculateRetryDelay]];
    } else {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 达到最大重试次数或暂停重试，停止重试"];
    }
}

- (void)setBannerDelegate
{
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 开始设置横幅广告代理"];
    
    if (self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 启用双广告位加载模式"];
        [self loadDualBannerAds];
    } else {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 使用单广告位加载模式"];
        [self loadBanner];
    }
}

- (void)showBanner
{
    [self showBannerForScene:DMBannerSceneLevelEnter];
}

- (void)showBannerWithScene:(IMAdScene)scene
{
    // 将IMAdScene转换为DMBannerScene
    DMBannerScene bannerScene;
    switch (scene) {
        case IMAdSceneBannerInit:
            bannerScene = DMBannerSceneInit;
            break;
        case IMAdSceneBannerLevelEnter:
            bannerScene = DMBannerSceneLevelEnter;
            break;
        default:
            bannerScene = DMBannerSceneLevelEnter; // 默认场景
            break;
    }
    
    // 调用新的场景化接口
    [self showBannerForScene:bannerScene];
}

- (void)performBannerShowWithScene:(DMBannerScene)scene
{
    
    // 如果 Banner 已经在显示，进行位置校正而不是直接忽略
    if (self.lpmBannerAdView && self.lpmBannerAdView.superview) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ⚠️ Banner已显示，开始位置校正以匹配当前参数 (isTop=%@)", self.isTop ? @"YES" : @"NO"];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIViewController *rootVC = [self topViewController];
            if (!rootVC) {
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 根控制器不存在，跳过位置校正"];
                return;
            }
            UIView *rootView = rootVC.view;
            if (!rootView) {
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 根视图不存在，跳过位置校正"];
                return;
            }
            // 若当前不在根视图下，先迁移到根视图
            if (self.lpmBannerAdView.superview != rootView) {
                [self.lpmBannerAdView removeFromSuperview];
                [rootView addSubview:self.lpmBannerAdView];
            }

            // 确保尺寸有效
            CGSize bannerSize = self.lpmBannerAdView.frame.size;
            if (bannerSize.width <= 0 || bannerSize.height <= 0) {
                if ([self.lpmBannerAdView respondsToSelector:@selector(intrinsicContentSize)]) {
                    CGSize intrinsic = self.lpmBannerAdView.intrinsicContentSize;
                    if (intrinsic.width > 0 && intrinsic.height > 0) {
                        bannerSize = intrinsic;
                    }
                }
            }
            if (bannerSize.width <= 0 || bannerSize.height <= 0) {
                LPMAdSize *fallbackSize = [LPMAdSize bannerSize];
                bannerSize = CGSizeMake(fallbackSize.width, fallbackSize.height);
            }
            if (bannerSize.width <= 0 || bannerSize.height <= 0) {
                bannerSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 50.0);
            }
            CGRect ensureFrame = self.lpmBannerAdView.frame;
            ensureFrame.size = bannerSize;
            self.lpmBannerAdView.frame = ensureFrame;

            // 依据 isTop 调整位置
            if (@available(iOS 11.0, *)) {
                CGFloat safeAreaTop = rootView.safeAreaInsets.top;
                CGFloat safeAreaBottom = rootView.safeAreaInsets.bottom;
                if (self.isTop) {
                    CGPoint topPosition = CGPointMake(rootView.center.x, safeAreaTop + (bannerSize.height/2.0));
                    [self.lpmBannerAdView setCenter:topPosition];
                    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 校正为顶部位置: (%.1f, %.1f)", topPosition.x, topPosition.y];
                } else {
                    CGPoint bottomPosition = CGPointMake(rootView.center.x,
                                                         rootView.frame.size.height - safeAreaBottom - (bannerSize.height/2.0));
                    [self.lpmBannerAdView setCenter:bottomPosition];
                    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 校正为底部位置: (%.1f, %.1f)", bottomPosition.x, bottomPosition.y];
                }
            } else {
                if (self.isTop) {
                    CGPoint topPosition = CGPointMake(rootView.center.x, (bannerSize.height/2.0));
                    [self.lpmBannerAdView setCenter:topPosition];
                    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 校正为顶部位置: (%.1f, %.1f)", topPosition.x, topPosition.y];
                } else {
                    CGPoint bottomPosition = CGPointMake(rootView.center.x, rootView.frame.size.height - (bannerSize.height/2.0));
                    [self.lpmBannerAdView setCenter:bottomPosition];
                    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 校正为底部位置: (%.1f, %.1f)", bottomPosition.x, bottomPosition.y];
                }
            }
        });
        return;
    }
    
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ========== 开始展示横幅广告 =========="];
    
    // 双广告位模式下选择最优广告位
    if (self.isDualAdEnabled) {
        NSString *selectedAdUnitId = [self selectOptimalAdUnitId];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 双广告位模式 - 选择的广告位ID: %@", selectedAdUnitId];
        
        // 根据选择的广告位ID设置当前使用的广告实例
        if ([selectedAdUnitId isEqualToString:self.currentPrimaryAdUnitId]) {
            self.lpmBannerAdView = self.primaryBannerAdView;
            self.currentAdUnitId = self.currentPrimaryAdUnitId;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 使用主广告位展示"];
        } else {
            self.lpmBannerAdView = self.secondaryBannerAdView;
            self.currentAdUnitId = self.currentSecondaryAdUnitId;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 使用备用广告位展示"];
        }
    }
    
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 当前状态检查:"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - Banner View 存在: %@", self.lpmBannerAdView ? @"YES" : @"NO"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - 广告已加载: %@", self.isLoadBanner ? @"YES" : @"NO"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - 位置设置: %@", self.isTop ? @"顶部" : @"底部"];
    
    // SDK_ad_show_request 广告展示请求事件打点
    self.currentAdScene = @"banner_show"; // 设置广告场景
    NSDictionary *showRequestParams = @{
        @"w_ad_scene": self.currentAdScene,
        @"w_ad_type": @"banner"
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_request" properties:showRequestParams];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_show_request"];
    
    if (self.lpmBannerAdView && self.isLoadBanner){
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ✅ 横幅广告准备就绪，开始安全展示检查"];
        
        // 🔒 安全检查1：应用状态
        UIApplicationState appState = [UIApplication sharedApplication].applicationState;
                 if (appState != UIApplicationStateActive) {
             [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ❌ 应用非活跃状态 (%ld)，延迟展示", (long)appState];
             
             // SDK_ad_show_fail 广告展示失败事件打点
             NSDictionary *showFailParams = @{
                 @"w_ad_scene": self.currentAdScene ?: @"banner_show",
                 @"w_ad_type": @"banner",
                 @"w_error_code": @"app_inactive",
                 @"w_error_msg": [NSString stringWithFormat:@"应用非活跃状态: %ld", (long)appState]
             };
             [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
             [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_show_fail (应用非活跃)"];
             
             self.hasShowAd = YES;  // 设置延迟展示标志
             self.showRequestTime = [[NSDate date] timeIntervalSince1970];  // 记录请求时间
             return;
         }
        
        // 🔒 安全检查2：根视图控制器可见性
        UIViewController *rootViewController = [self topViewController];
                 if (!rootViewController.view.window) {
             [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ❌ 根视图控制器不在窗口中，延迟展示"];
             
             // SDK_ad_show_fail 广告展示失败事件打点
             NSDictionary *showFailParams = @{
                 @"w_ad_scene": self.currentAdScene ?: @"banner_show",
                 @"w_ad_type": @"banner",
                 @"w_error_code": @"view_not_in_window",
                 @"w_error_msg": @"根视图控制器不在窗口中"
             };
             [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
             [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_show_fail (视图不在窗口)"];
             
             self.hasShowAd = YES;  // 设置延迟展示标志
             self.showRequestTime = [[NSDate date] timeIntervalSince1970];  // 记录请求时间
             return;
         }
        
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ✅ 安全检查通过，开始展示和布局"];
        
        self.isReloadBanner = NO;
        self.hasShowAd = NO;  // 确保清空延迟展示标志
        self.showRequestTime = 0;  // 清空时间戳
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 埋点事件已发送: adShow"];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 设置 isReloadBanner = NO"];
        
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 使用已验证的根控制器进行布局: %@", rootViewController];
        
        CGSize bannerSize = self.lpmBannerAdView.frame.size;
        // 兜底：若尺寸为0，尝试使用intrinsicSize或默认Banner尺寸
        if (bannerSize.width <= 0 || bannerSize.height <= 0) {
            if ([self.lpmBannerAdView respondsToSelector:@selector(intrinsicContentSize)]) {
                CGSize intrinsic = self.lpmBannerAdView.intrinsicContentSize;
                if (intrinsic.width > 0 && intrinsic.height > 0) {
                    bannerSize = intrinsic;
                }
            }
        }
        if (bannerSize.width <= 0 || bannerSize.height <= 0) {
            LPMAdSize *fallbackSize = [LPMAdSize bannerSize];
            bannerSize = CGSizeMake(fallbackSize.width, fallbackSize.height);
        }
        if (bannerSize.width <= 0 || bannerSize.height <= 0) {
            bannerSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 50.0);
        }
        // 确保视图具备有效尺寸
        CGRect ensureFrame = self.lpmBannerAdView.frame;
        ensureFrame.size = bannerSize;
        self.lpmBannerAdView.frame = ensureFrame;
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 横幅广告尺寸: %.1f x %.1f", bannerSize.width, bannerSize.height];
        
        if (@available(iOS 11.0, *)) {
            CGFloat safeAreaTop = rootViewController.view.safeAreaInsets.top;
            CGFloat safeAreaBottom = rootViewController.view.safeAreaInsets.bottom;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] iOS 11+ 安全区域: 顶部=%.1f, 底部=%.1f", safeAreaTop, safeAreaBottom];
            
            if (self.isTop) {
                CGPoint topPosition = CGPointMake(rootViewController.view.center.x, safeAreaTop + (bannerSize.height/2.0));
                [self.lpmBannerAdView setCenter:topPosition];
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 设置顶部位置: (%.1f, %.1f)", topPosition.x, topPosition.y];
            } else {
                CGPoint bottomPosition = CGPointMake(rootViewController.view.center.x,
                                                     rootViewController.view.frame.size.height - safeAreaBottom - (bannerSize.height / 2.0));
                [self.lpmBannerAdView setCenter:bottomPosition];
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 设置底部位置: (%.1f, %.1f)", bottomPosition.x, bottomPosition.y];
            }
        } else {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] iOS 11以下版本，使用传统布局"];
            if (self.isTop) {
                CGPoint topPosition = CGPointMake(rootViewController.view.center.x, (bannerSize.height/2.0));
                [self.lpmBannerAdView setCenter:topPosition];
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 设置顶部位置: (%.1f, %.1f)", topPosition.x, topPosition.y];
            } else {
                CGPoint bottomPosition = CGPointMake(rootViewController.view.center.x, rootViewController.view.frame.size.height - (bannerSize.height/2.0));
                [self.lpmBannerAdView setCenter:bottomPosition];
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 设置底部位置: (%.1f, %.1f)", bottomPosition.x, bottomPosition.y];
            }
        }
        [rootViewController.view addSubview:self.lpmBannerAdView];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ✅ 横幅广告已添加到视图层级"];
        
        // 更新广告展示记录
        IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
        IMAdScene adScene = IMAdSceneFromDMBannerScene(scene);
        [strategyManager updateAdShowRecord:adScene level:1];
        
        // 通知DMAdDelegate Banner展示成功
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didShowBannerForScene:adId:)]) {
        [self.delegate dmAdManager:(DMAdManager *)self didShowBannerForScene:self.currentAdScene ?: @"banner_show" adId:self.currentAdUnitId ?: @"banner_ad"];
        }
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 回调通知: onBannerShow"];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ✅ 广告展示记录已更新"];
    } else {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ❌ 横幅广告未准备就绪，设置延迟展示"];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 失败原因: %@",
              !self.lpmBannerAdView ? @"Banner View 不存在" : @"广告未加载完成"];
        
        if (self.isDualAdEnabled) {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 双广告位状态:"];
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - 主广告位已加载: %@", self.isPrimaryAdLoaded ? @"YES" : @"NO"];
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - 备用广告位已加载: %@", self.isSecondaryAdLoaded ? @"YES" : @"NO"];
        } else {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 失败原因: %@",
                  !self.lpmBannerAdView ? @"Banner View 不存在" : @"广告未加载完成"];
        }
        
        self.hasShowAd = YES;
        self.showRequestTime = [[NSDate date] timeIntervalSince1970];  // 记录请求时间
        self.isReloadBanner = YES;
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 设置状态: hasShowAd=YES, isReloadBanner=YES"];
        
        // SDK_ad_show_fail 广告展示失败事件打点
        NSDictionary *showFailParams = @{
            @"w_ad_scene": self.currentAdScene ?: @"banner_show",
            @"w_ad_type": @"banner",
            @"w_error_code": @"no_banner_view",
            @"w_error_msg": @"no bannerviwe"
        };
        [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:showFailParams];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_show_fail"];
        
        // 通知DMAdDelegate Banner展示失败
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowBannerForScene:error:)]) {
        NSError *error = [NSError errorWithDomain:@"DMBannerManager" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"Banner展示失败"}];
        [self.delegate dmAdManager:(DMAdManager *)self didFailToShowBannerForScene:self.currentAdScene ?: @"banner_show" error:error];
        }
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 回调通知: onBannerShowFail"];
        // 根据是否启用双广告位选择重新加载方式
        if (self.isDualAdEnabled) {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 重新加载双广告位"];
            [self loadDualBannerAds];
        } else {
            [self reLoad];
        }
    }
}

- (void)closeBanner
{
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 🔄 ========== 关闭横幅广告并重新加载 =========="];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 埋点事件已发送: adClose"];
    
    // 通知DMAdDelegate Banner被移除
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didRemoveBannerForScene:adId:)]) {
        [self.delegate dmAdManager:(DMAdManager *)self didRemoveBannerForScene:self.currentAdScene ?: @"banner_close" adId:self.currentAdUnitId ?: @"banner_ad"];
    }
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 回调通知: onBannerRemoved"];
    
    self.isUserClosed = NO; // 这是自动关闭，允许重新加载
    [self destroyBannerWithReload:YES];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 开始重新加载下一个横幅广告..."];
//    [self reLoad];
    // 根据是否启用双广告位选择重新加载方式
    if (self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 重新加载双广告位"];
        [self loadDualBannerAds];
    } else {
        [self loadBanner];
    }
}

- (void)hideBanner
{
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 🚫 ========== 用户主动隐藏横幅广告 =========="];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 此操作将关闭广告，并在后台预加载但不展示"];
    
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 埋点事件已发送: adClose"];
    
    // 通知DMAdDelegate Banner被移除
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didRemoveBannerForScene:adId:)]) {
        [self.delegate dmAdManager:(DMAdManager *)self didRemoveBannerForScene:self.currentAdScene ?: @"banner_hide" adId:self.currentAdUnitId ?: @"banner_ad"];
    }
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 回调通知: onBannerRemoved"];
    
    self.isUserClosed = YES; // 用户主动关闭，后续仅允许预加载，不自动展示
    [self destroyBannerWithReload:NO];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ✅ 横幅广告已彻底关闭"];

    // 优化：关闭后立即进行后台预加载（不展示）
    dispatch_async(dispatch_get_main_queue(), ^{
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 🔄 关闭后开始后台预加载（不展示）"];
        [self preloadBannerOnly];
    });
}

- (void)resumeBanner
{
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 🔄 ========== 重新启用横幅广告 =========="];
    self.isUserClosed = NO;
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 用户关闭状态已重置: isUserClosed = NO"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 现在可以正常加载和展示横幅广告"];
    // 根据是否启用双广告位选择重新加载方式
    if (self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 重新加载双广告位"];
        [self loadDualBannerAds];
    } else {
        [self loadBanner];
    }
}

- (void)checkPendingBannerDisplay
{
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 🔍 检查是否有待展示的横幅广告"];
    
    if (self.hasShowAd && self.lpmBannerAdView && self.isLoadBanner && !self.isUserClosed) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 发现待展示广告，尝试安全展示"];
        [self showBanner];
    } else {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 无待展示广告或条件不满足"];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - hasShowAd: %@", self.hasShowAd ? @"YES" : @"NO"];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - bannerView存在: %@", self.lpmBannerAdView ? @"YES" : @"NO"];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - 已加载: %@", self.isLoadBanner ? @"YES" : @"NO"];
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - 用户未关闭: %@", self.isUserClosed ? @"NO" : @"YES"];
    }
}

- (void)setBannerDirectionWithTop:(BOOL)topDir
{
    self.isTop = topDir;
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 设置横幅广告位置: %@", topDir ? @"顶部" : @"底部"];
}

- (void)destroyBanner {
    [self destroyBannerWithReload:YES];
}

- (void)destroyBannerWithReload:(BOOL)shouldReload {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 🗑️ ========== 销毁横幅广告 =========="];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 销毁后是否重新加载: %@", shouldReload ? @"YES" : @"NO"];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        // 销毁主广告位实例
        if (self.primaryBannerAdView) {
            [self.primaryBannerAdView removeFromSuperview];
            [self.primaryBannerAdView destroy];
            self.primaryBannerAdView = nil;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 主广告位实例已销毁"];
        }
        
        // 销毁备用广告位实例
        if (self.secondaryBannerAdView) {
            [self.secondaryBannerAdView removeFromSuperview];
            [self.secondaryBannerAdView destroy];
            self.secondaryBannerAdView = nil;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 备用广告位实例已销毁"];
        }
        
        // 销毁当前显示的广告实例
        if (self.lpmBannerAdView) {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 开始销毁现有 Banner View"];
            self.isLoadBanner = NO;
            [self.lpmBannerAdView removeFromSuperview];
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] Banner View 已从视图层级移除"];
            
            [self.lpmBannerAdView destroy];
            self.lpmBannerAdView = nil;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] Banner View 已销毁并置空"];
        } else {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 无需销毁，Banner View 不存在"];
        }
        
        self.hasShowAd = NO;
        self.showRequestTime = 0;  // 清空时间戳
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 重置状态: hasShowAd = NO"];
        
        // 重置双广告位状态
        if (self.isDualAdEnabled) {
            self.isPrimaryAdLoaded = NO;
            self.isSecondaryAdLoaded = NO;
            self.isLoadingPrimary = NO;
            self.isLoadingSecondary = NO;
            self.primaryAdECPM = 0.0;
            self.secondaryAdECPM = 0.0;
            self.primaryAdLoadTime = 0;
            self.secondaryAdLoadTime = 0;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 双广告位状态已重置"];
        }
        
        if (shouldReload && !self.isUserClosed) {
//            WDLog(@"🏷️ [Banner] 开始加载新的横幅广告...");
//            [self loadBanner];
        } else {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 不进行自动重载 (destroy阶段)"];
        }
    });
}

#pragma mark LPMBannerAdViewDelegate

- (void)didLoadAdWithAdInfo:(LPMAdInfo *)adInfo {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ✅ ========== 横幅广告加载成功 =========="];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] AdInfo详情:"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - AdNetwork: %@", adInfo.adNetwork ?: @"N/A"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - AdUnit: %@", adInfo.adUnitId ?: @"N/A"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - InstanceId: %@", adInfo.instanceId ?: @"N/A"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - InstanceName: %@", adInfo.instanceName ?: @"N/A"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - Revenue: $%.6f", adInfo.revenue ? adInfo.revenue.doubleValue : 0.0];
    
    // 判断是主广告位还是备用广告位加载成功
    BOOL isPrimaryAd = NO;
    BOOL isSecondaryAd = NO;
    NSString *adSource = @"single";
    
    if (self.isDualAdEnabled) {
        if ([adInfo.adUnitId isEqualToString:self.currentPrimaryAdUnitId]) {
            isPrimaryAd = YES;
            adSource = @"primary";
            self.isPrimaryAdLoaded = YES;
            self.isLoadingPrimary = NO;
            self.primaryAdECPM = adInfo.revenue ? adInfo.revenue.doubleValue : 0.0;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 主广告位加载成功，ECPM: %.6f", self.primaryAdECPM];
        } else if ([adInfo.adUnitId isEqualToString:self.currentSecondaryAdUnitId]) {
            isSecondaryAd = YES;
            adSource = @"secondary";
            self.isSecondaryAdLoaded = YES;
            self.isLoadingSecondary = NO;
            self.secondaryAdECPM = adInfo.revenue ? adInfo.revenue.doubleValue : 0.0;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 备用广告位加载成功，ECPM: %.6f", self.secondaryAdECPM];
        }
    }
    
    // SDK_ad_fill_success 广告填充成功事件打点
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval fillTime = 0;
    if (isPrimaryAd && self.primaryAdLoadTime > 0) {
        fillTime = (currentTime - self.primaryAdLoadTime) * 1000;
    } else if (isSecondaryAd && self.secondaryAdLoadTime > 0) {
        fillTime = (currentTime - self.secondaryAdLoadTime) * 1000;
    } else {
        fillTime = (currentTime - self.loadStartTime) * 1000;
    }
    NSDictionary *fillSuccessParams = @{
        @"w_ad_type": @"banner",
        @"w_ad_unit_id": self.currentAdUnitId ?: @"",
        @"w_fill_time": @(fillTime),
        @"w_network": adInfo.adNetwork ?: @""
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_fill_success" properties:fillSuccessParams];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_fill_success"];
    
    // 通知DMAdDelegate广告加载成功
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didLoadBannerForScene:adId:)]) {
        [self.delegate dmAdManager:(DMAdManager *)self didLoadBannerForScene:self.currentAdScene ?: @"default" adId:self.currentAdUnitId ?: @"banner_ad"];
    }
    
    // 广告加载成功，重置重试状态
    [self resetRetryState];
    
    // 在双广告位模式下，只有当至少一个广告位加载成功时才设置isLoadBanner
    if (self.isDualAdEnabled) {
        if (self.isPrimaryAdLoaded || self.isSecondaryAdLoaded) {
            self.isLoadBanner = YES;
        }
    } else {
        self.isLoadBanner = YES;
    }
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 设置加载状态: isLoadBanner = YES"];
    
    UIViewController *rootViewController = [self topViewController];
    dispatch_async(dispatch_get_main_queue(), ^{
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 开始预设置广告位置 (加载时)"];
        
        // 选择需要预设置的目标Banner视图（双广告位时为刚加载成功的视图）
        LPMBannerAdView *targetBannerView = self.lpmBannerAdView;
        if (self.isDualAdEnabled) {
            if (isPrimaryAd) {
                targetBannerView = self.primaryBannerAdView;
            } else if (isSecondaryAd) {
                targetBannerView = self.secondaryBannerAdView;
            }
        }
        
        CGSize bannerSize = targetBannerView.frame.size;
        // 兜底：若尺寸为0，尝试使用intrinsicSize或默认Banner尺寸
        if (bannerSize.width <= 0 || bannerSize.height <= 0) {
            if ([targetBannerView respondsToSelector:@selector(intrinsicContentSize)]) {
                CGSize intrinsic = targetBannerView.intrinsicContentSize;
                if (intrinsic.width > 0 && intrinsic.height > 0) {
                    bannerSize = intrinsic;
                }
            }
        }
        if (bannerSize.width <= 0 || bannerSize.height <= 0) {
            LPMAdSize *fallbackSize = [LPMAdSize bannerSize];
            bannerSize = CGSizeMake(fallbackSize.width, fallbackSize.height);
        }
        if (bannerSize.width <= 0 || bannerSize.height <= 0) {
            bannerSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 50.0);
        }
        // 确保视图具备有效尺寸
        CGRect ensureFrame2 = targetBannerView.frame;
        ensureFrame2.size = bannerSize;
        targetBannerView.frame = ensureFrame2;
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 横幅广告尺寸: %.1f x %.1f", bannerSize.width, bannerSize.height];
        
        if (@available(iOS 11.0, *)) {
            CGFloat safeAreaTop = rootViewController.view.safeAreaInsets.top;
            CGFloat safeAreaBottom = rootViewController.view.safeAreaInsets.bottom;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 安全区域: 顶部=%.1f, 底部=%.1f", safeAreaTop, safeAreaBottom];
            
            if (self.isTop) {
                CGPoint topPosition = CGPointMake(rootViewController.view.center.x, safeAreaTop + (bannerSize.height/2.0));
                [targetBannerView setCenter:topPosition];
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 预设置顶部位置: (%.1f, %.1f)", topPosition.x, topPosition.y];
            } else {
                CGPoint bottomPosition = CGPointMake(rootViewController.view.center.x,
                                                     rootViewController.view.frame.size.height - safeAreaBottom - (bannerSize.height / 2.0));
                [targetBannerView setCenter:bottomPosition];
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 预设置底部位置: (%.1f, %.1f)", bottomPosition.x, bottomPosition.y];
            }
        } else {
            if (self.isTop) {
                CGPoint topPosition = CGPointMake(rootViewController.view.center.x, (bannerSize.height/2.0));
                [targetBannerView setCenter:topPosition];
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 预设置顶部位置: (%.1f, %.1f)", topPosition.x, topPosition.y];
            } else {
                CGPoint bottomPosition = CGPointMake(rootViewController.view.center.x, rootViewController.view.frame.size.height - (bannerSize.height/2.0));
                [targetBannerView setCenter:bottomPosition];
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 📍 预设置底部位置: (%.1f, %.1f)", bottomPosition.x, bottomPosition.y];
            }
        }
        
        if (self.hasShowAd) {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 检测到延迟展示标志，开始安全展示检查"];
            
            // 🔒 安全检查1：应用状态
            UIApplicationState appState = [UIApplication sharedApplication].applicationState;
            if (appState != UIApplicationStateActive) {
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ❌ 应用非活跃状态 (%ld)，取消展示以防刷量", (long)appState];
                
                // SDK_ad_show_fail 延迟展示失败事件打点
                NSDictionary *delayShowFailParams = @{
                    @"w_ad_scene": self.currentAdScene ?: @"banner_show",
                    @"w_ad_type": @"banner",
                    @"w_error_code": @"delay_app_inactive",
                    @"w_error_msg": [NSString stringWithFormat:@"延迟展示时应用非活跃状态: %ld", (long)appState]
                };
                [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:delayShowFailParams];
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_show_fail (延迟展示-应用非活跃)"];
                return;
            }
            
            // 🔒 安全检查2：根视图控制器可见性
            if (!rootViewController.view.window) {
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ❌ 根视图控制器不在窗口中，取消展示以防刷量"];
                
                // SDK_ad_show_fail 延迟展示失败事件打点
                NSDictionary *delayShowFailParams = @{
                    @"w_ad_scene": self.currentAdScene ?: @"banner_show",
                    @"w_ad_type": @"banner",
                    @"w_error_code": @"delay_view_not_in_window",
                    @"w_error_msg": @"延迟展示时根视图控制器不在窗口中"
                };
                [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:delayShowFailParams];
                [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_show_fail (延迟展示-视图不在窗口)"];
                return;
            }
            
                         // 🔒 安全检查3：延迟展示时间限制 (防止过期展示)
             NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
             NSTimeInterval timeSinceRequest = currentTime - self.showRequestTime;
             const NSTimeInterval maxDelayTime = 30.0; // 最大延迟30秒
             if (timeSinceRequest > maxDelayTime) {
                 [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ❌ 展示请求已过期 (%.1f秒前)，取消展示以防刷量", timeSinceRequest];
                 
                 // SDK_ad_show_fail 延迟展示失败事件打点
                 NSDictionary *delayShowFailParams = @{
                     @"w_ad_scene": self.currentAdScene ?: @"banner_show",
                     @"w_ad_type": @"banner",
                     @"w_error_code": @"delay_request_expired",
                     @"w_error_msg": [NSString stringWithFormat:@"延迟展示请求已过期: %.1f秒前", timeSinceRequest]
                 };
                 [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_fail" properties:delayShowFailParams];
                 [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_show_fail (延迟展示-请求过期)"];
                 return;
             }
             [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ✅ 展示请求未过期 (%.1f秒前)", timeSinceRequest];
            
                         [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ✅ 安全检查通过，执行延迟展示"];
             
             // 重置延迟展示标志
             self.hasShowAd = NO;
             self.showRequestTime = 0;
             
             [rootViewController.view addSubview:self.lpmBannerAdView];
             [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ✅ 横幅广告已安全展示"];
             
             // 延迟展示成功时的事件打点将由didDisplayAdWithAdInfo代理方法处理
            
            // 通知DMAdDelegate Banner展示成功 (延迟展示)
            if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didShowBannerForScene:adId:)]) {
                [self.delegate dmAdManager:(DMAdManager *)self didShowBannerForScene:self.currentAdScene ?: @"banner_show" adId:self.currentAdUnitId ?: @"banner_ad"];
            }
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 回调通知: onBannerShow (延迟展示)"];
        }
    });
}

- (void)didFailToLoadAdWithAdUnitId:(NSString *)adUnitId error:(NSError *)error {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ❌ ========== 横幅广告加载失败 =========="];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] AdUnit ID: %@", adUnitId];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 错误信息: %@", error.localizedDescription];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 错误代码: %ld", (long)error.code];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 错误域: %@", error.domain];
    if (error.userInfo) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 错误详情: %@", error.userInfo];
    }
    
    // 判断是主广告位还是备用广告位加载失败
    BOOL isPrimaryAdFailed = NO;
    BOOL isSecondaryAdFailed = NO;
    NSString *adSource = @"single";
    
    if (self.isDualAdEnabled) {
        if ([adUnitId isEqualToString:self.currentPrimaryAdUnitId]) {
            isPrimaryAdFailed = YES;
            adSource = @"primary";
            self.isLoadingPrimary = NO;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 主广告位加载失败"];
        } else if ([adUnitId isEqualToString:self.currentSecondaryAdUnitId]) {
            isSecondaryAdFailed = YES;
            adSource = @"secondary";
            self.isLoadingSecondary = NO;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 备用广告位加载失败"];
        }
    }
    
    
    // SDK_ad_fill_fail 广告填充失败事件打点
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval fillTime = 0;
    if (isPrimaryAdFailed && self.primaryAdLoadTime > 0) {
        fillTime = (currentTime - self.primaryAdLoadTime) * 1000;
    } else if (isSecondaryAdFailed && self.secondaryAdLoadTime > 0) {
        fillTime = (currentTime - self.secondaryAdLoadTime) * 1000;
    } else {
        fillTime = (currentTime - self.loadStartTime) * 1000;
    }
    NSDictionary *fillFailParams = @{
        @"w_ad_type": @"banner",
        @"w_ad_unit_id": adUnitId ?: @"",
        @"w_fill_time": @(fillTime),
        @"w_error_code": [NSString stringWithFormat:@"%ld", (long)error.code],
        @"w_error_msg": error.localizedDescription ?: @"",
        @"w_ad_source": adSource
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_fill_fail" properties:fillFailParams];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_fill_fail"];
    
    // 通知DMAdDelegate广告加载失败
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToLoadBannerForScene:error:)]) {
        NSError *sdkError = [NSError errorWithDomain:@"DualMediationSDK" code:error.code userInfo:@{NSLocalizedDescriptionKey: error.localizedDescription ?: @"Unknown error"}];
        [self.delegate dmAdManager:(DMAdManager *)self didFailToLoadBannerForScene:self.currentAdScene ?: @"default" error:sdkError];
    }
    
    
    // 双广告位模式下的失败处理逻辑
    if (self.isDualAdEnabled) {
        // 如果主广告位失败，检查是否可以切换到备用广告位
        if (isPrimaryAdFailed && self.isSecondaryAdLoaded) {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 主广告位失败，但备用广告位已就绪，切换到备用广告位"];
            [self switchToSecondaryAdIfNeeded];
            return; // 不触发失败回调，因为还有备用广告位可用
        }
        
        // 只有当双广告位都失败时才设置isLoadBanner = NO
        if (!self.isPrimaryAdLoaded && !self.isSecondaryAdLoaded && !self.isLoadingPrimary && !self.isLoadingSecondary) {
            self.isLoadBanner = NO;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 双广告位都失败，设置加载状态: isLoadBanner = NO"];
        } else {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 还有广告位在加载或已加载，不触发失败回调"];
        }
    } else {
        // 单广告位模式的原有逻辑
        self.isLoadBanner = NO;
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 设置加载状态: isLoadBanner = NO"];
    }
    
    if (self.isUserClosed) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 用户已主动关闭广告，不进行重试"];
        return;
    }
    
    // 使用智能重试机制
    if ([self shouldRetry]) {
        [self scheduleRetryWithDelay:[self calculateRetryDelay]];
    } else {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 达到最大重试次数或暂停重试，停止重试"];
    }
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 设置状态: isLoadBanner=NO, isReloadBanner=YES"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 将通过自动重加载机制重试"];
}

- (void)didClickAdWithAdInfo:(LPMAdInfo *)adInfo {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 👆 ========== 横幅广告被点击 =========="];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] AdInfo详情:"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - AdNetwork: %@", adInfo.adNetwork ?: @"N/A"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - InstanceId: %@", adInfo.instanceId ?: @"N/A"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - InstanceName: %@", adInfo.instanceName ?: @"N/A"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - Revenue: $%.6f", adInfo.revenue ? adInfo.revenue.doubleValue : 0.0];
    
    // SDK_ad_show_click 广告点击事件打点
    NSDictionary *clickParams = @{
        @"w_ad_scene": self.currentAdScene ?: @"banner_show",
        @"w_ad_type": @"banner",
        @"w_ad_unit_id": self.currentAdUnitId ?: @"",
        @"w_network": adInfo.adNetwork ?: @"",
        @"w_ad_revenue": adInfo.revenue ?: @(0.0)
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_click" properties:clickParams];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_show_click"];
    
    // 通知DMAdDelegate广告被点击
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didClickBannerForScene:adId:)]) {
        [self.delegate dmAdManager:(DMAdManager *)self didClickBannerForScene:self.currentAdScene ?: @"default" adId:self.currentAdUnitId ?: @"banner_ad"];
    }
}

- (void)didDisplayAdWithAdInfo:(LPMAdInfo *)adInfo {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ✅ ========== 横幅广告展示成功 =========="];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] AdInfo详情:"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - AdNetwork: %@", adInfo.adNetwork ?: @"N/A"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - InstanceId: %@", adInfo.instanceId ?: @"N/A"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - InstanceName: %@", adInfo.instanceName ?: @"N/A"];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner]   - Revenue: $%.6f", adInfo.revenue ? adInfo.revenue.doubleValue : 0.0];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 当前位置: %@", self.isTop ? @"顶部" : @"底部"];
    
    // SDK_ad_show_success 广告展示成功事件打点
    NSDictionary *showSuccessParams = @{
        @"w_ad_scene": self.currentAdScene ?: @"banner_show",
        @"w_ad_type": @"banner",
        @"w_ad_unit_id": self.currentAdUnitId ?: @"",
        @"w_network": adInfo.adNetwork ?: @"",
        @"w_ad_revenue": adInfo.revenue ?: @(0.0)
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_success" properties:showSuccessParams];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_show_success"];
    
    // SDK_ad_show_completed 广告播放完成事件打点 (Banner广告展示即完成)
    NSDictionary *showCompletedParams = @{
        @"w_ad_scene": self.currentAdScene ?: @"banner_show",
        @"w_ad_type": @"banner",
        @"w_ad_unit_id": self.currentAdUnitId ?: @"",
        @"w_network": adInfo.adNetwork ?: @"",
        @"w_ad_revenue": adInfo.revenue ?: @(0.0)
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_show_completed" properties:showCompletedParams];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_show_completed"];
    
    // AD_Banner_show 横幅广告展示事件上报（场景+收入，收入单位mUSD）
    double ecpm = adInfo.revenue ? adInfo.revenue.doubleValue * 1000.0 : 0.0;
    NSString *scene = self.currentAdScene ?: @"banner_show";
    NSDictionary *bannerShowParams = @{ @"w_scene": scene, @"w_revenue": @(ecpm) };
    [[DMThinkingManager shareThinkingManager] thinkingTrackEventWithKey:@"AD_Banner_show" jsonStr:bannerShowParams];
    
    double revenueUSD = [[NSUserDefaults standardUserDefaults] doubleForKey:@"Banner_RevenueUSD"];
    if (revenueUSD > 0) {
        ADJAdRevenue *adjustAdRevenue = [[ADJAdRevenue alloc] initWithSource:@"ironsource_sdk"];
        [adjustAdRevenue setRevenue:revenueUSD currency:@"USD"];
        [adjustAdRevenue setAdRevenueNetwork:adInfo.adNetwork];
        [adjustAdRevenue setAdRevenueUnit:adInfo.adUnitId];
        [adjustAdRevenue setAdRevenuePlacement:adInfo.placementName];
        [adjustAdRevenue addPartnerParameter:@"ad_format" value: adInfo.adUnitId];
        [adjustAdRevenue addPartnerParameter:@"ad_unit_id" value: adInfo.instanceId];
        [adjustAdRevenue addPartnerParameter:@"auctionId" value:adInfo.auctionId];
        [Adjust trackAdRevenue:adjustAdRevenue];
    }
    
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件上报: AD_Banner_show, w_scene=%@, w_revenue=%.2f", scene, ecpm];
    
    // 通知DMAdDelegate广告展示成功
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didShowBannerForScene:adId:)]) {
        [self.delegate dmAdManager:(DMAdManager *)self didShowBannerForScene:self.currentAdScene ?: @"default" adId:self.currentAdUnitId ?: @"banner_ad"];
    }
}



#pragma mark - Banner重构接口实现

- (void)showBannerForScene:(DMBannerScene)scene {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 场景化Banner展示请求 - 场景: %ld", (long)scene];
    
    // 检查广告策略
    IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
    IMAdScene adScene = IMAdSceneFromDMBannerScene(scene);
    [strategyManager reportLevelBehavior:adScene level:1 onlineTime:0 completion:^(BOOL shouldShowAd, id condition) {
        if (!shouldShowAd) {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ❌ 广告策略检查失败，不展示广告"];
            
            // 通知DMAdDelegate广告展示失败
            if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowBannerForScene:error:)]) {
                NSError *error = [NSError errorWithDomain:@"DualMediationSDK" code:2001 userInfo:@{NSLocalizedDescriptionKey: @"Ad strategy check failed"}];
                [self.delegate dmAdManager:(DMAdManager *)self didFailToShowBannerForScene:[self stringFromBannerScene:scene] error:error];
            }
            return;
        }
        
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ✅ 广告策略检查通过，开始展示广告"];
        self.currentAdScene = [self stringFromBannerScene:scene];
        [self performBannerShowWithScene:scene];
    }];
}

- (void)hideBannerForScene:(DMBannerScene)scene {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 隐藏场景Banner - 场景: %ld", (long)scene];
    [self hideBanner];
    
    // 通知DMAdDelegate Banner已隐藏
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didRemoveBannerForScene:adId:)]) {
        [self.delegate dmAdManager:(DMAdManager *)self didRemoveBannerForScene:[self stringFromBannerScene:scene] adId:self.currentAdUnitId ?: @"banner_ad"];
    }
}

- (BOOL)isBannerReadyForScene:(DMBannerScene)scene {
    BOOL isReady = (self.lpmBannerAdView != nil && self.isLoadBanner && !self.isUserClosed);
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 检查Banner准备状态 - 场景: %ld, 状态: %@", (long)scene, isReady ? @"就绪" : @"未就绪"];
    return isReady;
}

- (void)showBannerAd:(DMBannerScene)scene position:(BannerPosition)position enableShortScreenDetection:(BOOL)enableShortScreenDetection {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 新接口Banner展示 - 场景: %ld, 位置: %ld, 短屏检测: %@", 
     (long)scene, (long)position, enableShortScreenDetection ? @"启用" : @"禁用"];
    
    // 设置Banner位置
    self.isTop = (position == BannerPositionTop);
    
    // 短屏检测逻辑
    if (enableShortScreenDetection) {
        CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
        if (screenHeight < 667.0) { // iPhone SE等小屏设备
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 检测到短屏设备 (高度: %.0f)，调整展示策略", screenHeight];
            // 短屏设备可能需要特殊处理，比如调整位置或不展示
        }
    }
    
    // 检查广告策略
    IMAdStrategyManager *strategyManager = [IMAdStrategyManager sharedManager];
    IMAdScene adScene = IMAdSceneFromDMBannerScene(scene);
    [strategyManager reportLevelBehavior:adScene level:1 onlineTime:0 completion:^(BOOL shouldShowAd, id condition) {
        if (!shouldShowAd) {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ❌ 广告策略检查失败，不展示广告"];
            
            // 通知DMAdDelegate广告展示失败
            if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToShowBannerForScene:error:)]) {
                NSError *error = [NSError errorWithDomain:@"DualMediationSDK" code:2001 userInfo:@{NSLocalizedDescriptionKey: @"Ad strategy check failed"}];
                [self.delegate dmAdManager:(DMAdManager *)self didFailToShowBannerForScene:[self stringFromBannerScene:scene] error:error];
            }
            return;
        }
        
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ✅ 广告策略检查通过，开始展示广告"];
        self.currentAdScene = [self stringFromBannerScene:scene];
        [self performBannerShowWithScene:scene];
    }];
}

- (void)preloadBannerForScene:(DMBannerScene)scene {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 预加载Banner - 场景: %ld", (long)scene];
    self.currentAdScene = [self stringFromBannerScene:scene];
    [self loadBanner];
}

- (void)destroyBannerForScene:(DMBannerScene)scene {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 销毁场景Banner - 场景: %ld", (long)scene];
    [self destroyBannerWithReload:NO];
    
    // 通知DMAdDelegate Banner已销毁
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didRemoveBannerForScene:adId:)]) {
        [self.delegate dmAdManager:(DMAdManager *)self didRemoveBannerForScene:[self stringFromBannerScene:scene] adId:self.currentAdUnitId ?: @"banner_ad"];
    }
}

#pragma mark - 辅助方法

- (NSString *)stringFromBannerScene:(DMBannerScene)scene {
    switch (scene) {
        case DMBannerSceneInit:
            return SCENE_BANNER_INIT;
        case DMBannerSceneLevelEnter:
            return SCENE_BANNER_LEVEL_ENTER;
        case DMBannerSceneLevelComplete:
            return SCENE_BANNER_LEVEL_WIN;
        case DMBannerSceneShop:
            return SCENE_BANNER_SHOP;
        case DMBannerSceneLevelFail:
            return SCENE_BANNER_LEVEL_FAIL;
        case DMBannerSceneGamePause:
            return SCENE_BANNER_GAME_PAUSE;
        case DMBannerSceneMainMenu:
            return SCENE_BANNER_MAIN_MENU;
        case DMBannerSceneSettings:
            return SCENE_BANNER_SETTINGS;
        default:
            return SCENE_BANNER_INIT; // 默认返回初始场景
    }
}

- (UIViewController *)topViewController {
    UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (rootVC.presentedViewController) {
        rootVC = rootVC.presentedViewController;
    }
    return rootVC;
}


#pragma mark - 双广告位支持方法

- (void)loadDualBannerAds {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ========== 开始加载双广告位横幅广告 =========="];
    
    if (!self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 双广告位未启用，回退到单广告位模式"];
        [self loadBanner];
        return;
    }
    
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 主广告位ID: %@", self.currentPrimaryAdUnitId];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 备用广告位ID: %@", self.currentSecondaryAdUnitId];
    
    // 并行加载主广告位和备用广告位
    [self loadPrimaryBannerAd];
    [self loadSecondaryBannerAd];
}

- (void)loadPrimaryBannerAd {
    if (!self.currentPrimaryAdUnitId || self.isLoadingPrimary) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 主广告位ID为空或正在加载中，跳过加载"];
        return;
    }
    
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ========== 开始加载主广告位 =========="];
    self.isLoadingPrimary = YES;
    self.primaryAdLoadTime = [[NSDate date] timeIntervalSince1970];
    
    // 记录广告加载请求到WDCommercialSDK
    [[DMCommercialManager sharedInstance] recordAdLoadRequest:self.currentPrimaryAdUnitId adType:@"banner"];
    
    // SDK_ad_fill_request 广告填充请求事件打点
    NSDictionary *fillRequestParams = @{
        @"w_ad_type": @"banner",
        @"w_ad_unit_id": self.currentPrimaryAdUnitId,
        @"w_ad_source": @"primary"
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_fill_request (主广告位)"];
    
    // 创建主广告位实例（带尺寸配置，避免0x0尺寸）
    LPMAdSize *primaryAdSize = [LPMAdSize bannerSize];
    LPMBannerAdViewConfig *primaryConfig = [[[[LPMBannerAdViewConfigBuilder alloc] init] setWithAdSize:primaryAdSize] build];
    self.primaryBannerAdView = [[LPMBannerAdView alloc] initWithAdUnitId:self.currentPrimaryAdUnitId config:primaryConfig];
    self.primaryBannerAdView.frame = CGRectMake(0, 0, primaryAdSize.width, primaryAdSize.height);
    self.primaryBannerAdView.delegate = self;
    
    // 开始加载
    [self.primaryBannerAdView loadAdWithViewController:[self topViewController]];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 主广告位开始加载: %@", self.currentPrimaryAdUnitId];
}

- (void)loadSecondaryBannerAd {
    if (!self.currentSecondaryAdUnitId || self.isLoadingSecondary) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 备用广告位ID为空或正在加载中，跳过加载"];
        return;
    }
    
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ========== 开始加载备用广告位 =========="];
    self.isLoadingSecondary = YES;
    self.secondaryAdLoadTime = [[NSDate date] timeIntervalSince1970];
    
    // 记录广告加载请求到WDCommercialSDK
    [[DMCommercialManager sharedInstance] recordAdLoadRequest:self.currentSecondaryAdUnitId adType:@"banner"];
    
    // SDK_ad_fill_request 广告填充请求事件打点
    NSDictionary *fillRequestParams = @{
        @"w_ad_type": @"banner",
        @"w_ad_unit_id": self.currentSecondaryAdUnitId,
        @"w_ad_source": @"secondary"
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_ad_fill_request" properties:fillRequestParams];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 事件打点: SDK_ad_fill_request (备用广告位)"];
    
    // 创建备用广告位实例（带尺寸配置，避免0x0尺寸）
    LPMAdSize *secondaryAdSize = [LPMAdSize bannerSize];
    LPMBannerAdViewConfig *secondaryConfig = [[[[LPMBannerAdViewConfigBuilder alloc] init] setWithAdSize:secondaryAdSize] build];
    self.secondaryBannerAdView = [[LPMBannerAdView alloc] initWithAdUnitId:self.currentSecondaryAdUnitId config:secondaryConfig];
    self.secondaryBannerAdView.frame = CGRectMake(0, 0, secondaryAdSize.width, secondaryAdSize.height);
    self.secondaryBannerAdView.delegate = self;
    
    // 开始加载
    [self.secondaryBannerAdView loadAdWithViewController:[self topViewController]];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 备用广告位开始加载: %@", self.currentSecondaryAdUnitId];
}

- (NSString *)selectOptimalAdUnitId {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ========== 选择最优广告位 =========="];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 主广告位状态: %@, ECPM: %.6f", self.isPrimaryAdLoaded ? @"已加载" : @"未加载", self.primaryAdECPM];
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 备用广告位状态: %@, ECPM: %.6f", self.isSecondaryAdLoaded ? @"已加载" : @"未加载", self.secondaryAdECPM];
    
    // 如果主广告位已加载且备用广告位未加载，选择主广告位
    if (self.isPrimaryAdLoaded && !self.isSecondaryAdLoaded) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 选择主广告位（备用广告位未加载）"];
        return self.currentPrimaryAdUnitId;
    }
    
    // 如果备用广告位已加载且主广告位未加载，选择备用广告位
    if (self.isSecondaryAdLoaded && !self.isPrimaryAdLoaded) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 选择备用广告位（主广告位未加载）"];
        return self.currentSecondaryAdUnitId;
    }
    
    // 如果两个广告位都已加载，比较ECPM选择更优的
    if (self.isPrimaryAdLoaded && self.isSecondaryAdLoaded) {
        if (self.primaryAdECPM >= self.secondaryAdECPM) {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 选择主广告位（ECPM更高: %.6f vs %.6f）", self.primaryAdECPM, self.secondaryAdECPM];
            return self.currentPrimaryAdUnitId;
        } else {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 选择备用广告位（ECPM更高: %.6f vs %.6f）", self.secondaryAdECPM, self.primaryAdECPM];
            return self.currentSecondaryAdUnitId;
        }
    }
    
    // 如果都未加载，默认返回主广告位ID
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 两个广告位都未加载，默认选择主广告位"];
    return self.currentPrimaryAdUnitId;
}

- (void)switchToSecondaryAdIfNeeded {
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] ========== 检查是否需要切换到备用广告位 =========="];
    
    if (!self.isDualAdEnabled) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 双广告位未启用，无需切换"];
        return;
    }
    
    if (!self.isPrimaryAdLoaded && self.isSecondaryAdLoaded) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 主广告位加载失败，备用广告位已就绪，切换到备用广告位"];
        
        // 切换当前使用的广告位
        self.currentAdUnitId = self.currentSecondaryAdUnitId;
        self.lpmBannerAdView = self.secondaryBannerAdView;
        self.isLoadBanner = YES;
        
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 已切换到备用广告位: %@", self.currentSecondaryAdUnitId];
        
        // 重新加载主广告位
        [self loadPrimaryBannerAd];
    } else {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 无需切换广告位"];
    }
}

// impressionDataDidSucceed 回调已统一到 WDIronSourceManager 中处理

#pragma mark - 智能重试机制

/**
 * 初始化重试设置
 */
- (void)initializeRetrySettings {
    self.maxRetryCount = 5;  // 最大重试次数
    self.retryCount = 0;     // 当前重试次数
    self.totalLoadAttempts = 0;  // 总加载尝试次数
    self.totalFailureCount = 0;  // 总失败次数
    self.lastRetryTime = 0;      // 上次重试时间
    self.isRetryPaused = NO;     // 是否暂停重试
    self.retryTimer = nil;       // 重试定时器
    
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 重试设置初始化完成 - 最大重试次数: %ld", (long)self.maxRetryCount];
}

/**
 * 重置重试状态
 */
- (void)resetRetryState {
    [self cancelRetryTimer];
    self.retryCount = 0;
    self.isRetryPaused = NO;
    self.lastRetryTime = 0;
    
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 重试状态已重置"];
}

/**
 * 安排延迟重试
 * @param delay 延迟时间（秒）
 */
- (void)scheduleRetryWithDelay:(NSTimeInterval)delay {
    [self cancelRetryTimer];
    
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 安排 %.1f 秒后重试 (第 %ld/%ld 次)", delay, (long)(self.retryCount + 1), (long)self.maxRetryCount];
    
    __weak typeof(self) weakSelf = self;
    self.retryTimer = [NSTimer scheduledTimerWithTimeInterval:delay repeats:NO block:^(NSTimer * _Nonnull timer) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf) {
            [strongSelf performRetry];
        }
    }];
}

/**
 * 判断是否应该重试
 * @return YES表示应该重试，NO表示不应该重试
 */
- (BOOL)shouldRetry {
    // 检查是否暂停重试
    if (self.isRetryPaused) {
        NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
        NSTimeInterval pauseDuration = 30 * 60; // 30分钟
        
        if (currentTime - self.lastRetryTime < pauseDuration) {
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 重试已暂停，剩余暂停时间: %.1f 分钟", (pauseDuration - (currentTime - self.lastRetryTime)) / 60.0];
            return NO;
        } else {
            // 暂停时间已过，重置状态
            self.isRetryPaused = NO;
            self.retryCount = 0;
            [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 暂停时间已过，重置重试状态"];
        }
    }
    
    // 检查重试次数
    if (self.retryCount >= self.maxRetryCount) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 已达到最大重试次数 (%ld)，停止重试", (long)self.maxRetryCount];
        return NO;
    }
    
    // 检查失败率
    double failureRate = [self calculateFailureRate];
    if (failureRate > 0.8 && self.totalLoadAttempts >= 10) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 失败率过高 (%.1f%%)，暂停重试30分钟", failureRate * 100];
        self.isRetryPaused = YES;
        self.lastRetryTime = [[NSDate date] timeIntervalSince1970];
        return NO;
    }
    
    return YES;
}

/**
 * 计算重试延迟时间（指数退避算法）
 * @return 延迟时间（秒）
 */
- (NSTimeInterval)calculateRetryDelay {
    // 指数退避：5秒、10秒、20秒、40秒、80秒
    NSTimeInterval baseDelay = 5.0;
    NSTimeInterval delay = baseDelay * pow(2, self.retryCount);
    
    // 最大延迟80秒
    if (delay > 80.0) {
        delay = 80.0;
    }
    
    return delay;
}

/**
 * 执行重试
 */
- (void)performRetry {
    if (self.isUserClosed) {
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 用户已关闭广告，取消重试"];
        return;
    }
    
    self.retryCount++;
    self.lastRetryTime = [[NSDate date] timeIntervalSince1970];
    
    [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 执行第 %ld 次重试", (long)self.retryCount];
    
    if (self.isDualAdEnabled) {
        [self loadDualBannerAds];
    } else {
        [self loadBanner];
    }
}

/**
 * 取消重试定时器
 */
- (void)cancelRetryTimer {
    if (self.retryTimer) {
        [self.retryTimer invalidate];
        self.retryTimer = nil;
        [IMLogUtils info:IMLogTagBanner format:@"🏷️ [Banner] 重试定时器已取消"];
    }
}

/**
 * 计算失败率
 * @return 失败率（0.0-1.0）
 */
- (double)calculateFailureRate {
    if (self.totalLoadAttempts == 0) {
        return 0.0;
    }
    
    return (double)self.totalFailureCount / (double)self.totalLoadAttempts;
}
@end
